#!/usr/bin/python
#
# Copyright (C) 2008 rambla.be
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

""" Demo for using the RATS python client library."""

import time
import rawsc
import rawsc.service
from rawsc import rats
import rawsc.rats.service
try:
  from xml.etree import cElementTree as ElementTree
except ImportError:
  try:
    import cElementTree as ElementTree
  except ImportError:
    from elementtree import ElementTree

USER = "XXX"
PWD = "XXX"
SERVER = "rats.enc01.rambla.be"

SRC_FILENAME = "southern_rock_opera.mp4"
TGT_FILENAME = "white_noise.mp4"
LOCAL_FILE = "PATH_TO_LOCAL_SRC_FILE"
LOCAL_TRANSCODINGS_DIR = "PATH_TO_WRITABLE_DIR"
FORMAT_PROFILE = "XXX"
OUTPUT_PROFILE = "XXX"

try:
    # Create a Rass instance, passing it your login credentials and the base service uri
    client = rawsc.rats.service.RatsService(username=USER, password=PWD, server=SERVER)


    # create new input profile
    entry = client.createInput(name = "Bright nuw input profile", description="Retrieve files from my ftp server", base_uri="ftp://fpt.myserver.org/movies/", method="ftp")
    print "Created new input profile: %s\n" % entry.id.text

    # update the existing input entry
    entry.content.params.name.text = "MyFtp input"
    new_entry = client.updateInput(entry = entry)
    print "Changed name to: %s\n" % new_entry.content.params.name.text
    
    # get list of input profiles
    qry = rawsc.Query()
    qry["name_has"] = "MyFtp"
    feed = client.getInputFeed(query = qry)
    print "Retrieved feed of MyFtp input profiles:"
    for e in feed.entry:
        print "\nEntry URI: " + e.id.text
        print "Profile name: " + e.content.params.name.text

    # delete input profile
    client.delete(uri = new_entry.id.text)
    print "\nDeleted input profile with ID = %s\n" % new_entry.content.params.id.text


    # create new format profile
    format_entry = client.createFormat(name = "MySimpleMp4", description="Transcode to basic h264 video, aac audio", 
                                category = "formats", container = "mp4", video_codec = "h264", video_fps = "25.0", 
                                video_width = "320", video_bitrate = "256", video_deinterlace = "md", video_passes = "2", video_cq = "0.10",
                                audio_channel = "2", audio_codec = "aac", audio_bitrate = "64", audio_sample_rate = "22000", audio_passes = "2")
    print "Created new format profile: %s\n" % format_entry.id.text
    
    # update the existing format entry
    entry.content.params.name.text = "doh"
    new_entry = client.updateFormat(entry = entry)
    print "Changed name to: %s\n" % new_entry.content.params.name.text
     
    # get list of format profiles
    qry = rawsc.Query()
    qry["name_has"] = "oh"
    feed = client.getFormatFeed(query = qry)
    print "Retrieved feed of format profiles whose name contains oh:"
    for e in feed.entry:
        print "\nEntry URI: " + e.id.text
        print "Profile name: " + e.content.params.name.text
     
    # delete format profile
    client.delete(uri = new_entry.id.text)
    print "\nDeleted format profile with ID = %s\n" % new_entry.content.params.id.text


    # get job feed
    print "\nRetrieving job feed, showing most recent updated job only:\n"
    feed = client.getJobFeed()
    for e in feed.entry:
        print "retrieved job with ID = %s, status = %s" % (e.content.params.id.text, e.content.params.status.text)
        # see if it has a report attached
        if hasattr(e, "reports"):
            print "Displaying report parts for job = %s" % e.id.text
            for job in e.reports.report.job:
                print "Data for %s job (profile = %s, msg = %s):" % (job.action, job.profile, job.msg_attr) # note: job.msg_attr is different from job.msg (= element)
                print "msg: %s" % job.msg.text
                print "start_time: %s" % job.start_time.text
                print "end_time: %s" % job.end_time.text
                print "local_uri: %s" % job.local_uri.text
                print "src_filesize: %s" % job.src_filesize.text
                print "tgt_filesize: %s" % job.tgt_filesize.text
                print "public_uri: %s" % job.public_uri.text
                print "export_uri: %s" % job.export_uri.text
                print "method: %s" % job.method.text
                print "\n"
            break


except rawsc.service.Error, e:
    print "Error Response from server, contents = %s.\n" % str(e)
    error_dict = e[0] # error dict inside the first tuple elem
    print "status code : " + str(error_dict["status"]) + "\n"
    if error_dict.has_key("body"):
        print "error body : " + error_dict["body"] + "\n"
except rawsc.RawscException, e:
    print "RawscException caught, reason = %s.\n" % str(e)
except StandardError, e:
    print "StandardError caught, reason = %s.\n" % str(e)
except:
    print "unhandled exception caught\n"
